package com.caigou.security.exception;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by echisan on 2018/6/24
 *
 * @description:没有携带token或者token无效
 */
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        //返回json形式的错误信息
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //String reason = "统一处理，原因：" + e.getMessage();
        //response.getWriter().write(new ObjectMapper().writeValueAsString(reason));
        PrintWriter writer = response.getWriter();
        JSONObject object = new JSONObject();
        object.put("status",403);
        object.put("message","没有携带token或者token无效");
        object.put("data","");
        writer.write(object.toString());
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json; charset=utf-8");
//        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//        String reason = "统一处理，原因：" + authException.getMessage();
//        response.getWriter().write(new ObjectMapper().writeValueAsString(reason));
    }
}
